# -*- coding: utf-8 -*-
# @Time    : 2022/2/27 16:15
# @Author  : icedew
# @File    : airtestlib.py
# @Software: PyCharm
import os.path
import shutil

from airtest.core.api import connect_device, keyevent
from airtest.core.helper import G, log
from airtest.core.settings import Settings as ST
from airtest.report.report import simple_report

from base.basesettings import logdir, reportdir


def only_auto_setup(basedir=None, devices=None, project_root=None, compress=None):
    if basedir:
        if os.path.isfile(basedir):
            basedir = os.path.dirname(basedir)
        if basedir not in G.BASEDIR:
            G.BASEDIR.append(basedir)

        if devices:
            for dev in devices:
                connect_device(dev)
        if project_root:
            ST.PROJECT_ROOT = project_root
        if compress:
            ST.SNAPSHOT_QUALITY = compress


def only_set_logdir(logdir):
    if os.path.exists(logdir):
        shutil.rmtree(logdir)
    os.mkdir(logdir)
    ST.LOG_DIR = logdir
    G.LOGGER.set_logfile(os.path.join(ST.LOG_DIR, ST.LOG_FILE))



def logreporter(logname):
    def outer(func):
        def inner(self, *args, **kwargs):
            only_set_logdir(logdir + logname)
            try:
                arg = func(self, *args, **kwargs)
            except Exception as e:
                log(e,  snapshot=True)
                raise e
            finally:
                simple_report(__file__, logpath=logdir + logname, output=reportdir+logname+".html")
                while not self.poco(text="歌单").exists():
                    keyevent("BACK")
            return arg

        return inner

    return outer
